import {reactive, toRefs, ref } from "vue";
const useAsyncFn = (fn)=>{
    let data = reactive({value:undefined ,loading:false,err:undefined});
    let lastCallId = ref(0);
    const callBack = (...args)=>{
        data.loading = true;
        const callId = ++lastCallId.value; // 避免短时间内，多次触发。导致结果错乱
        fn(...args).then((res)=>{
            if(callId === lastCallId.value){
                data.value = res;
                data.loading = false;
            }
        },(err)=>{
            if(callId === lastCallId.value){
                data.err = err
                data.loading = false;
            }
        })
    }

    return [toRefs(data),callBack];
}

export default useAsyncFn